extends RefCounted
class_name TileAstar
##godot官方提供的astar寻路脚本
var _astar :AStarGrid2D

##初始化astar
func initialize(astarlayer:TileMapLayer,solid_cells:Array[Vector2i],cells_cost:Dictionary) ->void:
	_initialize_astar(astarlayer)
	_set_cells_solid(solid_cells)
	_set_cells_cost(cells_cost)

## 获取连接起点与终点的路径，start_position是路径起点，end_position是路径终点
func get_path_from_to(start_position:Vector2i,end_position:Vector2i,temp_solid_cells:Array[Vector2i]=[]) ->Array[Vector2i]:
	var _start_cell = start_position
	var _end_cell = end_position
	_set_cells_solid(temp_solid_cells)
	var path = _astar.get_id_path(_start_cell,_end_cell,true)
	_free_cells_solid(temp_solid_cells)
	return path

##初始化astar
func _initialize_astar(astarlayer:TileMapLayer):
	_astar = AStarGrid2D.new()
	_astar.region = astarlayer.get_used_rect()
	_astar.cell_size = astarlayer.tile_set.tile_size
	##切换寻路算法的模式，该寻路算法将忽略所有对角线，并且给出路径始终是正交的。
	_astar.diagonal_mode = AStarGrid2D.DIAGONAL_MODE_NEVER
	_astar.update()
##设置多个单元格为障碍物
func _set_cells_solid(solid_cells:Array[Vector2i]):
	for cell in solid_cells:
		_astar.set_point_solid(cell)
##设置障碍单元格为可通行单元格
func _free_cells_solid(solid_cells:Array[Vector2i]):
	for cell in solid_cells:
		_astar.set_point_solid(cell,false)
##设置单个单元格的移动需要
func _set_cells_cost(cells_cost:Dictionary):
	for cell in cells_cost:
		_astar.set_point_weight_scale(cell,cells_cost[cell])
